using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace CQWPWtihEditLinks
{
    /// <summary>
    ///     <xsl:param name="ListDefaultViewUrl" />
    ///     <xsl:if test="string-length($ListDefaultViewUrl) !=0">
    ///         <xsl:variable name="ListDefaultViewLink">
    ///            &lt;a href='<xsl:value-of select="$ListDefaultViewUrl"/>'&gt;Source list&lt;/a&gt;
    ///         </xsl:variable>
    ///         <xsl:value-of select="$ListDefaultViewLink" disable-output-escaping="yes"/>
    ///     </xsl:if>
    ///     
    ///     <xsl:variable name="ListItemDisplayLink">
    ///        &lt;a href='<xsl:value-of select="@ListItemDisplayUrl"/>'&gt;[View]&lt;/a&gt;
    ///     </xsl:variable>
    ///     <xsl:variable name="ListItemEditLink">
    ///        &lt;a href='<xsl:value-of select="@ListItemEditUrl"/>'&gt;[Edit]&lt;/a&gt;
    ///     </xsl:variable>
    ///     
    ///     <xsl:if test="string-length(@ListItemDisplayUrl) !=0">
    ///        <xsl:value-of select="$ListItemDisplayLink" disable-output-escaping="yes"/>
    ///     </xsl:if>
    ///     
    ///     <xsl:if test="string-length(@ListItemEditUrl) !=0">
    ///        <xsl:value-of select="$ListItemEditLink" disable-output-escaping="yes"/>
    ///     </xsl:if>        	
    /// </summary>
    [Guid("5faa0ac8-5b67-43d8-ab04-8ae0be8de693")]
    public class CQWPWithEditLinks : Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
    {

        public CQWPWithEditLinks()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        private bool rebinding = false;

        protected override void ModifyXsltArgumentList(Microsoft.SharePoint.WebPartPages.ArgumentClassWrapper argList)
        {
            if (rebinding) return;
            rebinding = true;

            base.ModifyXsltArgumentList(argList);

            if (!string.IsNullOrEmpty(base.ListName) && !string.IsNullOrEmpty(base.WebUrl))
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(base.WebUrl))
                {
                    SPList list = web.Lists[base.ListName];
                    if (list.DoesUserHavePermissions(SPBasePermissions.AddListItems | SPBasePermissions.ApproveItems | SPBasePermissions.DeleteListItems | SPBasePermissions.EditListItems | SPBasePermissions.ManageLists))
                    {
                        argList.AddParameter("ListDefaultViewUrl", string.Empty, list.DefaultViewUrl);
                    }
                }
            }

            if (this.Data != null)
            {
                System.Data.DataColumn lieu = this.Data.Columns.Add("ListItemEditUrl", typeof(string));
                System.Data.DataColumn lidu = this.Data.Columns.Add("ListItemDisplayUrl", typeof(string));

                foreach (System.Data.DataRow row in this.Data.Rows)
                {
                    Guid WebId = new Guid("{" + row["WebId"].ToString() + "}");
                    Guid ListId = new Guid("{" + row["ListId"].ToString() + "}");
                    int ItemId = int.Parse(row["ID"].ToString());

                    using (SPWeb web = SPContext.Current.Site.OpenWeb(WebId))
                    {
                        SPList list = web.Lists[ListId];
                        SPListItem listitem = list.GetItemById(ItemId);
                        if ( listitem.DoesUserHavePermissions(SPBasePermissions.EditListItems | SPBasePermissions.ViewFormPages) )
                        {
                            string DisplayFormUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl;
                            row[lidu] = string.Format("{0}?ID={1}&Source={2}", DisplayFormUrl, ItemId, Context.Server.UrlEncode(Context.Request.RawUrl));
                        }

                        if (listitem.DoesUserHavePermissions(SPBasePermissions.EditListItems | SPBasePermissions.ViewFormPages))
                        {
                            string EditFormUrl = string.Empty;
                            if (listitem.File.CheckOutStatus != SPFile.SPCheckOutStatus.None && listitem.File.CheckedOutBy.UserToken.CompareUser(web.CurrentUser.UserToken))
                            {
                                EditFormUrl = list.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl;
                            }
                            else
                            { // The item is not checked out to the current user
                                // Direct the user to the ViewForm where it can checkout and edit the item
                                EditFormUrl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl;
                            }
                            row[lieu] = string.Format("{0}?ID={1}&Source={2}", EditFormUrl, ItemId, Context.Server.UrlEncode(Context.Request.RawUrl));
                        }
                    }
                }
                this.DataBind();
            }
        }

    }
}
